package com.qujia.station.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.PayTypeEnum;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.ServletUtils;
import com.qujia.common.utils.spring.SpringUtils;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.framework.web.service.TokenService;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.AutomaticClassDto;
import com.qujia.station.domain.dto.AutomaticClassInfo;
import com.qujia.station.domain.vo.AutomaticClassInfoVo;
import com.qujia.station.enums.PrintEnum;
import com.qujia.station.mapper.AutomaticClassMapper;
import com.qujia.station.mapper.AutomaticClassTimeMapper;
import com.qujia.station.service.*;
import com.qujia.station.utils.FeiEPrinterUtil;
import com.qujia.station.utils.Methods;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author PC
 * @description 针对表【automatic_class(自动班结表)】的数据库操作Service实现
 * @createDate 2023-08-18 14:16:30
 */
@Service
@Slf4j
public class AutomaticClassServiceImpl extends ServiceImpl<AutomaticClassMapper, AutomaticClass>
        implements AutomaticClassService {

    @Autowired
    private AutomaticClassMapper automaticClassMapper;

    @Autowired
    private AutomaticClassTimeMapper automaticClassTimeMapper;

    @Autowired
    private IClassSettlementService classSettlementService;
    @Autowired
    private IStationService stationService;
    @Autowired
    private ClassSettlementCardService classSettlementCardService;
    @Autowired
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Autowired
    private IStationDeviceManageService stationDeviceManageService;

    @Autowired
    private RedisCache redisCache;


    @Override
    @Transactional
    public int insertAutomaticClass(AutomaticClassDto classDto) {

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser currentUser = loginUser.getUser();
        if (ObjectUtils.isEmpty(classDto)) {
            return 0;
        }
        for (AutomaticClassInfo automaticClassInfo : classDto.getAutomaticClassInfos()) {
            Station station = stationService.selectStationById(automaticClassInfo.getStationId());
            if (station.getStatus().equals("0")){
                throw new CustomException("停用油站不能开启自动班结");
            }
        }

        log.info("根据油企id获取班结信息：{}",currentUser.getEnterpriseId());
        //获取该油企下开启自动班结的油站
        List<AutomaticClassInfoVo> automaticClassVos = automaticClassMapper.selectByEnterpriseID(currentUser.getEnterpriseId());
        ArrayList<AutomaticClassInfo> automaticClassInfos = classDto.getAutomaticClassInfos().stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(AutomaticClassInfo::getStationId))), ArrayList::new));
        for (AutomaticClassInfo automaticClassInfo : automaticClassInfos) {
            List<String> knotTimes1 = automaticClassInfo.getKnotTimes();
            List<String> collect = knotTimes1.stream()
                    .distinct()
                    .filter(element -> knotTimes1.indexOf(element) != knotTimes1.lastIndexOf(element))
                    .collect(Collectors.toList());
            if (!collect.isEmpty()){
                throw new CustomException("班结时间不能重复");
            }
        }
        if (!automaticClassVos.isEmpty()) {
            for (AutomaticClassInfoVo automaticClassVo : automaticClassVos) {
                automaticClassMapper.deleteAutomaticClass(automaticClassVo.getStationId());
                automaticClassTimeMapper.deleteutomaticClassTime(automaticClassVo.getStationId());
                Station station = new Station();
                station.setStationId(automaticClassVo.getStationId());
                station.setIsAutomaticClass(0);
                stationService.updateStation(station);
            }
        }

        for (AutomaticClassInfo automaticClassInfo : automaticClassInfos) {
            Station stationName = stationService.selectStationById(automaticClassInfo.getStationId());

            for (String knotTime : automaticClassInfo.getKnotTimes()) {

                AutomaticClassTime build = AutomaticClassTime.builder()
                        .stationId(automaticClassInfo.getStationId())
                        .stationName(stationName.getStationName())
                        .knotTime(knotTime)
                        .build();
                automaticClassTimeMapper.insert(build);
            }
            AutomaticClass automaticClass = AutomaticClass.builder()
                    .stationId(automaticClassInfo.getStationId())
                    .stationName(stationName.getStationName())
                    .userId(currentUser.getUserId())
                    .userName(currentUser.getUserName())
                    .build();
            automaticClassMapper.insert(automaticClass);
            Station station = new Station();
            station.setStationId(automaticClassInfo.getStationId());
            station.setIsAutomaticClass(1);
            stationService.updateStation(station);
        }
        return 1;
    }

    @Override
    public AutomaticClassDto getAutomaticClass(Long id) {
        AutomaticClassDto automaticClassDto = new AutomaticClassDto();

        List<AutomaticClassInfoVo> automaticClassInfoVos = automaticClassMapper.selectByEnterpriseID(id);


        if (ObjectUtils.isNotEmpty(automaticClassInfoVos)) {
            Map<Long, List<AutomaticClassInfoVo>> acVosMap = automaticClassInfoVos.stream().collect(Collectors.groupingBy(AutomaticClassInfoVo::getStationId));

            List<AutomaticClassInfo> acDtoList = new ArrayList<>();

            for (Long stationId : acVosMap.keySet()) {
                AutomaticClassInfo automaticClassInfo = new AutomaticClassInfo();
                automaticClassInfo.setStationId(stationId);
                automaticClassInfo.setStationName(acVosMap.get(stationId).get(0).getStationName());

                List<AutomaticClassInfoVo> automaticClassInfoVos1 = acVosMap.get(stationId);
                List<String> knotTimes = automaticClassInfoVos1.stream().map(AutomaticClassInfoVo::getKnotTime).collect(Collectors.toList());

                automaticClassInfo.setKnotTimes(knotTimes);
                acDtoList.add(automaticClassInfo);
            }
            automaticClassDto.setAutomaticClassInfos(acDtoList);
            automaticClassDto.setIsAuto(1);
            return automaticClassDto;
        }

        automaticClassDto.setIsAuto(0);
        return automaticClassDto;
    }

    @SneakyThrows
    @Override
    public void createClassSe(ClassSettlement classSettlement) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        if (classSettlement.getClassEndTime() == null || classSettlement.getStationId() == null) {
            throw new Exception("参数不完整");
        }
        classSettlement.setCreateUser(classSettlement.getCreateUser());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);

        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        String startTime = null;
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", fmt.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
        // 调用方法获取总金额
        BigDecimal actualRechargeReceivedAmt = customerCardUseRecordService.getTotalAmtByConditions(params);
        //电子卡赠送金额
        BigDecimal actualRechargeGiftAmt = customerCardUseRecordService.getTotalPresentAmtByConditions(params);

        Object stationId = params.get("stationId");
        Station station = stationService.selectStationById((Long) stationId);
        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(classSettlement.getStationId());
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
            payOrder.setStartTime(endTimeMap.get("classEndTime").toString());
        }
        payOrder.setStatus("1");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(classSettlement.getClassEndTime().toInstant(), ZoneId.systemDefault());
        String formattedDate = outputFormatter.format(localDateTime);
        payOrder.setEndTime(formattedDate);
        //        List<PayOrder> within7DaysData = payOrderService.selectPayOrderListUserPaytime(payOrder);
        String no = simFmtBef.format(classSettlement.getClassEndTime()) + classSettlement.getStationId() + simFmtAft.format(classSettlement.getClassEndTime());
        if (actualRechargeReceivedAmt != null && actualRechargeReceivedAmt.compareTo(BigDecimal.ZERO) != 0 || actualRechargeGiftAmt != null && actualRechargeGiftAmt.compareTo(BigDecimal.ZERO) != 0) {
            ClassSettlement settlementonlyactualRechargeReceivedAmt = new ClassSettlement();
            settlementonlyactualRechargeReceivedAmt.setActualRechargeReceivedAmt(actualRechargeReceivedAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeGiftAmt(actualRechargeGiftAmt);
            settlementonlyactualRechargeReceivedAmt.setClassNo(no);
            settlementonlyactualRechargeReceivedAmt.setCreateUser(classSettlement.getCreateUser());
            settlementonlyactualRechargeReceivedAmt.setEquipmentCode("PC");
            settlementonlyactualRechargeReceivedAmt.setStationId((Long) stationId);
            settlementonlyactualRechargeReceivedAmt.setStationName(station.getStationName());
            settlementonlyactualRechargeReceivedAmt.setCreateName(classSettlement.getCreateName());
            try {
                if (startTime != null) {
                    settlementonlyactualRechargeReceivedAmt.setClassStartTime(fmt.parse(startTime));
                }
                settlementonlyactualRechargeReceivedAmt.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlementonlyactualRechargeReceivedAmt.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlementonlyactualRechargeReceivedAmt);
        }
        for (ClassSettlement settlement : classSettlements) {
            settlement.setCreateName(classSettlement.getCreateName());
            settlement.setCreateUser(classSettlement.getCreateUser());
            settlement.setEquipmentCode("PC");
            settlement.setClassNo(no);
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementService.insertClassSettlement(settlement);

        }
        //        无数据新增0班结 缺少新增字段
        if (classSettlements.size() == 0) {
            ClassSettlement settlement = new ClassSettlement();
            settlement.setCreateName(classSettlement.getCreateName());
            settlement.setCreateUser(classSettlement.getCreateUser());
            settlement.setClassNo(no);

            settlement.setStationId((Long) stationId);
            settlement.setStationName(station.getStationName());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlement.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlement);
        }
        for (ClassSettlementCard settlement : classSettlementCards) {
            settlement.setCreateName(classSettlement.getCreateName());
            settlement.setCreateUser(classSettlement.getCreateUser());
            settlement.setEquipmentCode("PC");
            settlement.setCreateTime(new Date());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            if (settlement.getClassEndTime() != null) {
                classSettlementCardService.insertClassSettlementCard(settlement);
            }

        }
        ClassSettlement pushClass = new ClassSettlement();
        pushClass.setClassNo(no);
        pushClass.setStationId(classSettlement.getStationId());
        pushClass.setClassEndTime(classSettlement.getClassEndTime());
        try {
            if (startTime != null) {
                pushClass.setClassStartTime(fmt.parse(startTime));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        getPushMessage(pushClass);
        resultMap.put("classNo", no);
    }

    @SneakyThrows
    @Override
    @Transactional
    public void deleteAutomaticClass(AutomaticClassDto classDto) {

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser currentUser = loginUser.getUser();
        log.info("根据油企id获取班结信息：{}", currentUser.getEnterpriseId());
        if (ObjectUtils.isEmpty(currentUser.getEnterpriseId())) {
            throw new Exception("没有获取到油企信息");
        }
        List<AutomaticClassInfoVo> automaticClassInfoVos = automaticClassMapper.selectByEnterpriseID(currentUser.getEnterpriseId());
        log.info("班结信息出参：{}", automaticClassInfoVos);
        if (!automaticClassInfoVos.isEmpty()) {
            for (AutomaticClassInfoVo automaticClassInfoVo : automaticClassInfoVos) {
                automaticClassMapper.deleteAutomaticClass(automaticClassInfoVo.getStationId());
                automaticClassTimeMapper.deleteutomaticClassTime(automaticClassInfoVo.getStationId());
                Station station = new Station();
                station.setStationId(automaticClassInfoVo.getStationId());
                station.setIsAutomaticClass(0);
                log.info("更新油站班级结状态入参：{}", station);
                stationService.updateStation(station);
            }
        }
    }

    public void getPushMessage(ClassSettlement classSettlement) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNo", classSettlement.getClassNo());

        //合计所有油品信息的集合
        List<ClassSettlement> sumOilList = classSettlementService.queryClassSettlementOil(queryMap);
        //合计班结信息，按照支付方式的集合
        List<ClassSettlement> sumPayTypeList = classSettlementService.queryClassSettlementPayType(queryMap);

        ClassSettlementCard classSettlementCard = new ClassSettlementCard();
        classSettlementCard.setClassNo(classSettlement.getClassNo());
        //合计班结信息，充值的信息集合
        List<ClassSettlementCard> sumCzList = classSettlementCardService.queryGroupByCardType(classSettlementCard);
        //合计  班结总计的信息集合
        List<ClassSettlement> sumClassList = classSettlementService.querySummaryByClassNo(queryMap);

        //加油员班结信息汇总
        List<ClassSettlement> oilPersonList = classSettlementService.selectClassSettlementSummaryUser(queryMap);
        //充值金额合计
        ClassSettlementCard classSettlementCardCz = classSettlementCardService.querySumCz(queryMap);

        List<Map<String, Object>> oilPersonClass = new ArrayList<>();
        for (int i = 0; i < oilPersonList.size(); i++) {
            Map<String, Object> person1 = new HashMap<>();
            person1.put("personName", oilPersonList.get(i).getOilPersonnelName());
            if (classSettlement.getClassStartTime() == null) {
                person1.put("classStartTime", "首次");
            } else {
                person1.put("classStartTime", fmt.format(classSettlement.getClassStartTime()));
            }
            person1.put("classEndTime", fmt.format(classSettlement.getClassEndTime()));
            Map<String, Object> queryMap1 = new HashMap<>();
            queryMap1.put("stationId", classSettlement.getStationId());
            queryMap1.put("classNo", classSettlement.getClassNo());
            queryMap1.put("oilPersonnelId", oilPersonList.get(i).getOilPersonnelId());
            //合计所有油品信息的集合
            List<ClassSettlement> OilList = classSettlementService.queryClassSettlementOil(queryMap);
            person1.put("oilList", OilList);
            person1.put("orderCount", oilPersonList.get(i).getOrderCount());
            person1.put("receivableAmt", oilPersonList.get(i).getReceivableAmt());
            person1.put("discountAmt", oilPersonList.get(i).getDiscountAmt());
            person1.put("refundAmt", oilPersonList.get(i).getRefundAmt());
            person1.put("amt", oilPersonList.get(i).getAmt());
            person1.put("oilPersonnelName", oilPersonList.get(i).getOilPersonnelName());
            oilPersonClass.add(person1);
        }
        Map<String, Object> sumClassMap = new HashMap<>();
        sumClassMap.put("sumClassList", sumClassList);
        sumClassMap.put("sumOilList", sumOilList);
        sumClassMap.put("sumPayTypeList", sumPayTypeList);
        sumClassMap.put("sumCzList", sumCzList);
        sumClassMap.put("oilPersonClass", oilPersonClass);
        this.feiePush(sumClassList, sumOilList, sumPayTypeList, sumCzList, oilPersonClass, classSettlementCardCz, classSettlement);

    }

    // 打印的班结小票的排版
    public void feiePush(List<ClassSettlement> sumClassList, List<ClassSettlement> sumOilList, List<ClassSettlement> sumPayTypeList, List<ClassSettlementCard> sumCzList, List<Map<String, Object>> oilPersonList, ClassSettlementCard czClass, ClassSettlement classSettlement) { //
        try {
            if (sumClassList == null || sumClassList.size() <= 0) {
                return;
            }
            Station station = stationService.selectStationById(sumClassList.get(0).getStationId());

            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(sumClassList.get(0).getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return;
            }
            StringBuilder content = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (true) {
                content.append("<BOLD><B>--班结小票----</B></BOLD><BR>");
                if (sumClassList.get(0).getClassStartTime() != null) {
                    content.append("开始时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                } else {
                    content.append("开始时间：" + "首次" + "<BR>");
                }
                if (sumClassList.get(0).getClassEndTime() != null) {
                    content.append("结束时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                }
                content.append("油品   笔数    升数     金额" + "<BR>");
                content.append("--------------------------" + "<BR>");

                for (ClassSettlement classSettlement1 : sumOilList) {
                    if (StringUtils.isEmpty(classSettlement1.getOilName())) {
                        continue;
                    }
                    content.append(classSettlement1.getOilName() + "     " + classSettlement1.getOrderCount() + "     " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("支付方式   笔数    升数     金额" + "<BR>");
                for (ClassSettlement classSettlement1 : sumPayTypeList) {
                    if (StringUtils.isEmpty(classSettlement1.getPayType())) {
                        continue;
                    }
                    content.append(PayTypeEnum.getByType(classSettlement1.getPayType()).getDes() + "    " + classSettlement1.getOrderCount() + "     " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                }
                content.append("--------------------------" + "<BR>");
                content.append("充值类型   笔数   金额" + "<BR>");
                if (!CollectionUtils.isEmpty(sumCzList)) {
                    for (ClassSettlementCard classSettlementCard : sumCzList) {
                        if (StringUtils.isEmpty(classSettlementCard.getRechargeType())) {
                            continue;
                        }
                        String des = "";
                        if (!StringUtils.isEmpty(classSettlementCard.getRechargeType())) {
                            des = PayTypeEnum.getByType(classSettlementCard.getRechargeType()).getDes();
                        }

                        content.append(des + "     " + classSettlementCard.getOrderCount() + "     " + classSettlementCard.getAmt() + "<BR>");
                    }
                }

                content.append("--------------------------" + "<BR>");
                if (sumClassList.get(0).getOrderCount() != null) {
                    content.append("小票张数：" + sumClassList.get(0).getOrderCount() + "<BR>");
                }

                if (sumClassList.get(0).getReceivableAmt() != null) {
                    content.append("消费金额：" + sumClassList.get(0).getReceivableAmt() + "<BR>");
                }
                if (sumClassList.get(0).getDiscountAmt() != null) {
                    BigDecimal discountAmountAmt = Objects.isNull(sumClassList.get(0).getDiscountAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountAmt();
                    BigDecimal discountCouponAmt = Objects.isNull(sumClassList.get(0).getDiscountCouponAmt()) ? BigDecimal.ZERO : sumClassList.get(0).getDiscountCouponAmt();
                    content.append("优惠金额：" + discountAmountAmt.add(discountCouponAmt) + "<BR>");
                }

                if (sumClassList.get(0).getRefundAmt() != null) {
                    content.append("退款金额：" + sumClassList.get(0).getRefundAmt() + "<BR>");
                }
                if (sumClassList.get(0).getAmt() != null) {
                    content.append("订单实收金额：" + sumClassList.get(0).getAmt() + "<BR>");
                }
                if (czClass != null && czClass.getAmt() != null) {
                    content.append("充值金额：" + czClass.getAmt() + "<BR>");
                }

//                if( czClass!=null&&czClass.getAmt() != null&&sumClassList.get(0).getAmt()!=null){
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt().add(czClass.getAmt())+ "<BR>");
//                }else if(sumClassList.get(0).getAmt()!=null) {
//                    content.append("订单充值合计：" + sumClassList.get(0).getAmt()+ "<BR>");
//                }else if(czClass!=null&&czClass.getAmt()!=null){
//                    content.append("订单充值合计：" + czClass.getAmt()+ "<BR>");
//                }
                content.append("-------------------------<BR>");
                content.append("<BR>");
                content.append("<BR>");
                content.append("<BR>");
                Boolean personFlage = false;
                if (station != null && station.getClassPersonFlag() != null && station.getClassPersonFlag().equals("1")) {
                    for (Map<String, Object> oilPerson : oilPersonList) {
                        content.append("<BOLD><B>-班结小票---" + oilPerson.get("oilPersonnelName") + "-</B></BOLD><BR>");
                        if (sumClassList.get(0).getClassStartTime() != null) {
                            content.append("开始时间：" + sdf.format(sumClassList.get(0).getClassStartTime()) + "<BR>");
                        } else {
                            content.append("开始时间：" + "首次" + "<BR>");
                        }
                        if (sumClassList.get(0).getClassEndTime() != null) {
                            content.append("结束时间：" + sdf.format(sumClassList.get(0).getClassEndTime()) + "<BR>");
                        }
                        content.append("油品   笔数    升数     金额" + "<BR>");
                        content.append("--------------------------" + "<BR>");
                        List<ClassSettlement> oilList = (List<ClassSettlement>) oilPerson.get("oilList");
                        for (ClassSettlement classSettlement1 : oilList) {
                            content.append(classSettlement1.getOilName() + "   " + classSettlement1.getOrderCount() + "    " + classSettlement1.getOrderLiters() + "    " + classSettlement1.getAmt() + "<BR>");
                        }
                        content.append("--------------------------" + "<BR>");
                        if (oilPerson.get("orderCount") != null) {
                            content.append("小票张数：" + oilPerson.get("orderCount") + "<BR>");
                        }

                        if (oilPerson.get("receivableAmt") != null) {
                            content.append("消费金额：" + oilPerson.get("receivableAmt") + "<BR>");
                        }
                        if (oilPerson.get("discountAmt") != null) {
                            content.append("优惠金额：" + oilPerson.get("discountAmt") + "<BR>");
                        }

                        if (oilPerson.get("refundAmt") != null) {
                            content.append("退款金额：" + oilPerson.get("refundAmt") + "<BR>");
                        }
                        if (oilPerson.get("amt") != null) {
                            content.append("订单实际支付金额：" + oilPerson.get("amt") + "<BR>");
                        }
                        content.append("<BR>");
                        content.append("<BR>");
                    }
                }
            }
            content.append("<BR>");
            content.append("<BR>");
            StationDeviceManage stationDevice = stationDeviceManages.get(0);
            String deviceFactory = stationDevice.getDeviceFactory();

            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
            switch (printEnum) {
                case YILIANYUN:
                    String audio = "<audio>班结信息已打印</audio>";

                    String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>", "").replace("<BOLD><B>", "");
                    //初始化控制器类
                    Methods m = Methods.getInstance();
                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDevice.getClientId());

                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);

                    if (Objects.nonNull(token)) {
                        String print = m.print(stationDevice.getDeviceNo(), audio + ylyContent.toString(), random6.toString());
                        log.info("小票机返回值{}", print);
                        JSONObject json = new JSONObject(print);
                        if ("0".equals(json.getString("error"))) {
                            break;
                        }
                    }

                    //初始化终端信息
                    m.init(stationDevice.getClientId(), stationDevice.getClientSecret());
                    //获取token
                    String refreshToken = m.getFreedomToken();
                    //存入redis
                    redisCache.setCacheObject("STATION:DEVICE:" + stationDevice.getClientId(), refreshToken, 30, TimeUnit.DAYS);


                    String print = m.print(stationDevice.getDeviceNo(), audio + ylyContent, random6.toString());
                    log.info("小票机返回值2{}", print);
                    break;
                case FEIE:
                    FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), content.toString());
                    break;
            }
            //修改小票打印状态
            classSettlementService.updateClassSettlementPrintStatus(classSettlement.getClassNo());

            return;
        } catch (Exception e) {
            log.error(">pushConsumeToUser", e);
            return;
        }

    }
}




